package io.github.novaframe.web.util;

import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具
 * @author xn045342
 * @date 2018/7/4
 */
public class CookieUtil {

    public static void create(HttpServletResponse httpServletResponse, String name, String value, Boolean secure, Integer maxAge, String domain) {
        Cookie cookie = new Cookie(name, value);
        cookie.setSecure(secure); // secure=true => 仅仅能在 HTTPS 连接中被浏览器传递到服务器端进行会话验证
        cookie.setHttpOnly(true); // 使得 Javascript 脚本不能读取 cookies
        cookie.setMaxAge(maxAge); // 设置 Cookies 的过期值. maxAge=0 => 立即过期, maxAge=-1 => 永不过期
        cookie.setDomain(domain); // Cookies 仅对设置的域名可见
        cookie.setPath("/"); // Cookies 对所有路径可见
        httpServletResponse.addCookie(cookie);
    }
    public static void clear(HttpServletResponse httpServletResponse, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0);
        httpServletResponse.addCookie(cookie);
    }
    public static String getValue(HttpServletRequest httpServletRequest, String name) {
        Cookie cookie = WebUtils.getCookie(httpServletRequest, name);
        return cookie != null ? cookie.getValue() : null;
    }

}
